/*
 * @Author: xinyang3
 * @Date: 2021-10-08 15:50
 * @Descripttion: router user
 * @LastEditors: xinyang3
 * @LastEditTime: 2021-11-10 11:52
 */
import router from './router.js';
import * as CollectionUsers from '../collection/user.js';

const url_prifix = '/bgmg/user';

function stringify(result) {
  return JSON.stringify({
    type: 'succss',
    state: 200,
    data: result
  });
}

router.get(`${url_prifix}/list`, async ({ request, response }, next) => {
  const query = request.query;
  const result = await CollectionUsers.query(query);
  response.body = {
    type: 'succss',
    state: 200,
    data: result
  };
});

router.post(`${url_prifix}/insert`, async ({ request, response }, next) => {
  const data = request.body;
  const result = await CollectionUsers.insert(data);
  response.body = stringify(result);
});

router.post(`${url_prifix}/update`, async ({ request, response }, next) => {
  const data = request.body;
  const result = await CollectionUsers.update(data);
  response.body = stringify(result);
});

router.delete(
  `${url_prifix}/deleteOne`,
  async ({ request, response }, next) => {
    const query = request.query;
    const result = await CollectionUsers.deleteOne(query);
    response.body = stringify(result);
  }
);

router.get(`${url_prifix}/detail`, async ({ request, response }, next) => {
  const query = request.query;
  const result = await CollectionUsers.queryOne(query);
  response.body = stringify(result);
});

router.post(`${url_prifix}/login`, async (ctx, next) => {
  const { request, response } = ctx;
  const data = request.body;
  const user = await CollectionUsers.login(data);
  let valid = false;
  if (user && user.name) {
    valid = true;
    ctx.session[`bgmg-${user.name}`] = data.pwd;
    // ctx.session = Object.assign({}, { 'bgmg-name': pwd }, ctx.session);
  }
  response.body = stringify({ valid: valid, name: data.name, _id: user._id });
});
